<?php

/**
 * 会员商品报名管理
 * File Name：GoodsbmController.php
 * File Encoding：UTF-8
 * File New Time：2014-8-20 9:58:20
 * Author：水平凡
 * Mailbox：admin@abc3210.com
 */
class GoodsbmController extends UserLoginBaseC {

    //我的钱包
    public function actionMoney() {
        $MembersMoneyModel = new MembersMoneyModel();
        $money = $MembersMoneyModel->getUserMoney(Yii::app()->user->id);
        $this->render('money', array(
            'money' => $money,
        ));
    }

    //我的广告位
    public function actionAd() {
        $MoneyPositionOrderModel = new MoneyPositionOrderModel();
        $ads = $MoneyPositionOrderModel->getMenberAds(Yii::app()->user->id);
        $this->render('ad', array(
            'ads' => $ads[0],
            'pages' => $ads[1],
        ));
    }

    //报名宝贝
    public function actionGoods() {
        $GoodsBmModel = new GoodsBmModel();
        $label = (int) Yii::app()->request->getParam('label');
        $goods = $GoodsBmModel->getMemberBms($label);
        $count = $GoodsBmModel->getGoodsBmCount();
        $CategoryModel = new CategoryModel();
        $cats = $CategoryModel->getList();
        $username = Yii::app()->user->username;
        $this->render('goods', array(
            'goods' => $goods[0],
            'pages' => $goods[1],
            'username' => $username,
            'count' => $count,
            'label' => $label,
            'cats' => $cats,
        ));
    }

    //广告位兑换
    public function actionPayGoods() {
        $GoodsBmModel = new GoodsBmModel();
        $uid = Yii::app()->user->id;
        $goods = $GoodsBmModel->getMemberPayBms($uid);
        $CategoryModel = new CategoryModel();
        $cats = $CategoryModel->getList();
        $UserInfoModel = new MembersModel();
        $this->render('ad_change', array(
            'goods' => $goods[0],
            'pages' => $goods[1],
            'cats' => $cats,
            'pay_btn' => 1,
        ));
    }

    public function actionBmedit() {
        $goods_id = Yii::app()->request->getParam('goods_id');
        $model = GoodsBmModel::model();
        $data = $model->find($model->where(array('goods_id' => $goods_id, 'uid' => Yii::app()->user->id, 'status' => 0, 'pay_status' => array('IN', array(0, 1)), 'admin_id' => 0)));
        if (empty($data)) {
            $this->error('该信息不存在，或者不允许编辑！');
        }
        //添加的信息//找出付款类型来
        $order = MoneyPositionOrderModel::model()->find('uid = :uid and status = 0 and goods_bm_id = :goods_bm_id', array('uid' => Yii::app()->user->id, 'goods_bm_id' => $goods_id));
        if($order){
            $position_id = $order->payment_types;
        }else{
            $position_id = 0;
        }
        $this->assign('position_id', $position_id);  
        if (IS_POST) {
            //过滤不允许修改的内容
            $model->filterPostData($_POST);
            $data->attributes = $_POST;
            $return = $data->checkPaybm($position_id); 
            if(is_array($return)){
                if($return['status']){
                    empty($return['url']) ? $this->success($return['info']) : $this->success($return['info'], $return['url']);
                }else{
                    empty($return['url']) ? $this->error($return['info']) : $this->error($return['info'], $return['url']);
                }
            }else{
                $this->success('报名信息修改成功！', self::U($data->pay_status != 0 ? 'paygoods' : 'goods'));
            }
        } else {
            $this->assign('model', $model)
                    ->assign('data', $data)
                    ->render($data->pay_status != 0 ? 'paybm_edit' : '');
        }
    }

    //付费报名
    public function actionPaybm() {

        //$this->error('暂时无法付费报名，请联系客服！');
        $position_id = empty($_GET['position_id']) ? 7 : $_GET['position_id'];
        //收费类型
        $position = MoneyPositionModel::model()->getPositionInfo($position_id);
        if (empty($position)) {
            $this->error('付费类型不存在！');
        }

        $user = MembersModel::model()->findByPk(Yii::app()->user->id);
        if (empty($user)) {
            $this->error('获取用户信息失败！');
        }
        //手机是否绑定
        $phone = Yii::app()->user->phone;
        if (empty($phone)) {
            $this->error('请绑定手机后再报名！', self::U('info/index'));
        }
        $model = new GoodsBmModel();
        if (IS_POST) {
            //过滤不允许直接提交的内容
            $model->filterPostData($_POST);
            $model->attributes = $_POST;
            //各付费类型可能由于验证方式不太一样，需要封装在一个方法里面
            $return = $model->checkPaybm($position_id);            
            if(is_array($return)){
                if($return['status']){
                    empty($return['url']) ? $this->success($return['info']) : $this->success($return['info'], $return['url']);
                }else{
                    empty($return['url']) ? $this->error($return['info']) : $this->error($return['info'], $return['url']);
                }
            }

            $goods_id = $model->primaryKey;
            //添加日志
            GoodsActionModel::model()->goodsBmAdd($model);
            Yii::import('ext.alipay.*');
            $alipay = new Alipay();
            //推荐会员
            $recommend_uid = 0;
            //创建订单信息
            $orders = array(
                'type' => 0,
                'uid' => Yii::app()->user->id,
                'recommend_uid' => $recommend_uid,
                'order_title' => $position->title, //根据支付类型获取支付标题
                'product_id' => $model->product_id,
                'goods_name' => $model->goods_name,
                'price' => $model->p_price, //商品价格
                'money' => $position->money, //支付金额
                'goods_bm_id' => $goods_id,
                'payment_types' => $position->id, //支付类型ID
            );
            if ($alipay->data($orders)->createOrders() !== true) {
                $error = $alipay->getError();
                $this->error($error ? $error : '订单创建失败，请重新提交！');
            }
            //更新对应的报名信息状态
            if ($model->goodsBmPayChange($model) !== true) {
                $this->error('出现错误，请重试！', self::U('pay', array('goods_id' => $goods_id)));
            }
            //跳转到支付宝支付页面
            $url = $alipay->payment('', true);
            if ($url == false) {
                $error = $alipay->getError();
                $this->error($error ? $error : '订单处理错误！');
            } else {
                $this->success('报名成功，马上前往支付页面！', $url);
                exit;
            }
            
        }
        $this->assign('model', $model);
        empty($position->template) ? $this->render() : $this->render($position->template);
    }

    //订单支付
    public function actionPay() {
        $goods_id = Yii::app()->request->getParam('goods_id');
        if(Yii::app()->request->getParam('position_id')){
            $position_id = Yii::app()->request->getParam('position_id');
        }else{
            $position_id = 7;
        }
         $this->assign('position_id', $position_id);
        $model = GoodsBmModel::model();
        if ($_GET['undone']) {
            $order = MoneyPositionOrderModel::model()->find('uid = :uid and status = 0 and goods_bm_id = :goods_bm_id', array('uid' => Yii::app()->user->id, 'goods_bm_id' => $goods_id));
            Yii::import('ext.alipay.*');
            $alipay = new Alipay();
            //跳转到支付宝支付页面
            if ($alipay->payment($order) == false) {
                $error = $alipay->getError();
                $this->error($error ? $error : '订单处理错误！');
            }
            exit;
        }
        $data = $model->find($model->where(array('goods_id' => $goods_id, 'uid' => Yii::app()->user->id, 'status' => 0, 'pay_status' => 0)));
        if($position_id == 9){
            $year = date('Y');
            $data->start_time = strtotime($year . '-11-11 00:00:00');
            $data->end_time = strtotime($year . '-11-14 00:00:00');            
        }        
        if (empty($data)) {
            $this->error('没有找到符合付款要求的报名信息！');
        }
        if (IS_POST) {
            //如果等于9的支付类型则把开始时间跟结束时间固定写成双11的。
            if($position_id == 9){
                $data->special_id = 5;
                $data->save(false, array('start_time', 'end_time, special_id'));         
            }            
            Yii::import('ext.alipay.*');
            $alipay = new Alipay();
            //推荐会员
            $recommend_uid = 0;
            if (!empty($_POST['recommend_uid'])) {
                $userInfo = MembersModel::model()->find('username = :username', array('username' => $_POST['recommend_uid']));
                if (!empty($userInfo)) {
                    $recommend_uid = $userInfo->uid;
                }
            }
            //收费类型
            $position = MoneyPositionModel::model()->getPositionInfo($position_id);
            if (empty($position)) {
                $this->error('付费类型不存在！');
            }
            //创建订单信息
            $orders = array(
                'type' => 0,
                'uid' => Yii::app()->user->id,
                'recommend_uid' => $recommend_uid,
                'order_title' => $position->title, //根据支付类型获取支付标题
                'product_id' => $data->product_id,
                'goods_name' => $data->goods_name,
                'price' => $data->p_price, //商品价格
                'money' => $position->money, //支付金额
                'goods_bm_id' => $goods_id,
                'payment_types' => $position->id, //支付类型ID
            );
            if ($alipay->data($orders)->createOrders() !== true) {
                $error = $alipay->getError();
                $this->error($error ? $error : '订单创建失败，请重新提交！');
            }
            //更新对应的报名信息状态
            if ($model->goodsBmPayChange($data, $_POST['start_time']) !== true) {
                $this->error('出现错误，请重试！', self::U('pay', array('goods_id' => $goods_id)));
            }
            //跳转到支付宝支付页面
            if ($alipay->payment() == false) {
                $error = $alipay->getError();
                $this->error($error ? $error : '订单处理错误！');
            }
        } else {
            $this->assign('data', $data)
                    ->render();
        }
    }

    //确认邮寄样品
    public function actionSpecimen() {
        $goods_id = Yii::app()->request->getParam('goods_id');
        $model = GoodsBmModel::model();
        $data = $model->find($model->where(array('goods_id' => $goods_id, 'uid' => Yii::app()->user->id, 'status' => 3)));
        if (empty($data)) {
            $this->error('没有找到需要邮寄样品的报名信息！');
        } else if ($data->isdelivery == 2) {
            $this->error('已经确定收到了邮寄样品');
        }

        $objGoodsDelivery = GoodsDeliveryModel::model()->findByPk($goods_id);
        empty($objGoodsDelivery) ? $objGoodsDelivery = new GoodsDeliveryModel() : '';
        $_POST['goods_id'] = $goods_id;
        $objGoodsDelivery->attributes = $_POST;
        if (!$objGoodsDelivery->save()) {
            $this->error($objGoodsDelivery->getOneError());
        }

        if ($data->isdelivery != 1) {
            $data->isdelivery = 1;
            if (!$data->save(false, array('isdelivery'))) {
                $this->error('确认以邮寄样品失败！');
            }
        }
        $html_operation = $data->getMemberBmMayAction($data);
        $html_status = $data->getHtmlStatus($data);
        $arrData = array(
            'html_operation' => $html_operation,
            'html_status' => $html_status,
            'status' => 1,
            'info' => '处理成功',
        );
        echo json_encode($arrData);
        exit;
    }

    //取消报名
    public function actionCancel() {
        $goods_id = Yii::app()->request->getParam('goods_id');
        $model = GoodsBmModel::model();
        $data = $model->find($model->where(array('goods_id' => $goods_id, 'uid' => Yii::app()->user->id, 'status' => 0, 'pay_status' => array('IN', array(0, 1)), 'admin_id' => 0)));
        if (empty($data)) {
            $this->error('该信息无法取消报名！');
        }
        if ($model->cancelBm($data)) {
            $this->success('取消报名成功！');
        } else {
            $this->error('取消报名操作失败！');
        }
    }

    /**
     * 报名查询根据$product_id 查找gid 根据gid返回 最近的报名动作
     */
    public function actionQuery() {
        $product_id = trim(Yii::app()->request->getParam('product_id'));
        $good_id = (int) Yii::app()->request->getParam('goods_id');
        if (IS_POST) {
            $this->redirect(self::U('query', $_POST));
            exit;
        }
        $goodsAction = GoodsActionModel::model();
        $goodsBm = GoodsBmModel::model();
        if (!empty($product_id) && (int) $product_id > 0) {
            $goodsInfo = $goodsBm->find($goodsBm->where(array('product_id' => $product_id, 'order' => 'goods_id desc')));
            $good_id = $goodsInfo['goods_id'];
        }
        if (empty($good_id)) {
            $this->error('未找到报名商品，请检查查询ID是否正确！');
        }

        $cacheKey = md5("actionQuery_{$good_id}");
        $cache = Yii::app()->cache->get($cacheKey);
        if (!empty($cache)) {
            $this->render('goods_bminfo', $cache);
            return true;
        }
        $goodsInfo = $goodsBm->find($goodsBm->where(array('goods_id' => $good_id)));
        if (!empty($goodsInfo)) {
            $goods['goods_id'] = $goodsInfo->goods_id;
            $goods['product_id'] = $goodsInfo->product_id;
            $goods['title'] = $goodsInfo->goods_name;
            $goods['detail_url'] = $goodsInfo->detail_url;
            $goods['pic_url'] = $goodsInfo->product_img;
            $goods['promo_price'] = $goodsInfo->promo_price;
            $goods['cat_id'] = $goodsInfo->cat_id;
            $goods['stock'] = $goodsInfo->stock;
            $goods['status'] = $goodsInfo->status;
            $goods['note'] = isset($goodsInfo->note) ? $goodsInfo->note : '';
            $goods['isdelivery'] = $goodsInfo->isdelivery;
            $goods['admin'] = $goodsInfo->admin_id;
            $goods['is_show_wangwang'] = $goodsInfo->is_show_wangwang;
            $product_id = $goods['product_id'];
            $start_time = $goodsInfo->start_time;
            $end_time = $goodsInfo->end_time;
        } else {
            $this->error('未找到报名商品，请检查查询ID是否正确！');
        }
        if (!empty($goods['admin'])) {
            $adminuserModel = new AdminUser();
            $adminuser = $adminuserModel->getUserInfo((int) $goods['admin']);
            $goods['admin'] = $adminuser['wangwang'];
        }
        //历史报名记录
        $goodsbmlistModel = $goodsBm->findAll($goodsBm->where(array('product_id' => $product_id, 'order' => 'goods_id DESC')));
        $goodsbmlist = array();
        foreach ($goodsbmlistModel as $key => $value) {
            $action = $goodsAction->find($goodsAction->where(array('gid' => $value->goods_id, 'order' => 'action_time DESC')));
            //修改报名时间, 以及最后一个动作的结束时间
            $goodsbmlist[$value->goods_id] = $value;
            $goodsbmlist[$value->goods_id]->start_time = $action->baoming_time;
            $goodsbmlist[$value->goods_id]->end_time = $action->action_time;
        }
        $actionList = $goodsAction->findAll($goodsAction->where(array('gid' => $good_id, 'order' => 'action_time ASC')));
        if (!empty($actionList)) {
            foreach ($actionList AS $key => $value) {
                $value = $value->attributes;
                $audit_list[$key]['m_d'] = date('m月d日', $value['action_time']);
                $audit_list[$key]['h_i_s'] = date('H:i:s', $value['action_time']);
                $audit_list[$key]['note'] = $value['note'];
                $audit_list[$key]['action_type'] = $value['action_type'];
                if ($audit_list[$key]['action_type'] == 0) {
                    $audit_list[$key]['status'] = '商家报名';
                    $audit_list[$key]['note_title'] = '';
                    $audit_list[$key]['note'] = '';
                } else if ($audit_list[$key]['action_type'] == 1) {
                    $audit_list[$key]['status'] = '审核通过';
                    $audit_list[$key]['note_title'] = '审核通过：';
                    $audit_list[$key]['note'] = '上架时间：' . date('Y-m-d H:i:s', $start_time) . " 至 " . date('Y-m-d H:i:s', $end_time);
                } else if ($audit_list[$key]['action_type'] == 2) {
                    $audit_list[$key]['status'] = '审核不通过';
                    $audit_list[$key]['note_title'] = '审核建议：';
                } else if ($audit_list[$key]['action_type'] == 3) {
                    $audit_list[$key]['status'] = '删除商品';
                    $audit_list[$key]['note_title'] = '';
                    $audit_list[$key]['note'] = '';
                } else if ($audit_list[$key]['action_type'] == 4) {
                    $audit_list[$key]['status'] = '手动添加！';
                    $audit_list[$key]['note_title'] = '';
                    $audit_list[$key]['note'] = '';
                } else if ($audit_list[$key]['action_type'] == 5) {
                    $audit_list[$key]['status'] = '邮寄样品中';
                    $audit_list[$key]['note_title'] = '邮寄样品：';
                } else if ($audit_list[$key]['action_type'] == 6) {
                    $audit_list[$key]['status'] = '用户取消报名';
                    $audit_list[$key]['note_title'] = '';
                    $audit_list[$key]['note'] = '';
                }
                $goods['note_title'] = $audit_list[$key]['note_title'];
                $goods['note'] = $audit_list[$key]['note'];
            }
        } else {
            $this->error('未找到报名商品，请检查查询ID是否正确！');
        }
        $cache = array(
            'goods' => $goods,
            'audit_list' => $audit_list,
            'goodsbmlist' => $goodsbmlist,
        );
        Yii::app()->cache->set($cacheKey, $cache, 60);
        $this->render('goods_bminfo', $cache);
    }

}
